<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { API_CONFIG } from '../config/apiConfig';
import { ToastService } from '../utils/toastService';

const { t } = useI18n();
const username = ref('');
const password = ref('');
const router = useRouter();

  const handleLogin = async () => {
    try {
      // 清除之前的备份数据
      localStorage.removeItem('userInfo');
      document.cookie = 'token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';

      const response = await fetch(`${API_CONFIG.BASE_URL}/user/login`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username.value,
          password: password.value
        }),
        credentials: 'include' // 必须添加
      });
      
      const result = await response.json();
      
      if (result.code === "0") {
        // 存储完整的用户信息
        const userData = {
          id: result.data.id,
          username: result.data.username,
          nickname: result.data.nickname,
          roleId: result.data.roleId,
          roleName: result.data.roleName,
          permissions: result.data.permissions || [],
          researchRoleInfos: result.data.researchRoleInfos || {},
          knowledgeBaseGroupRoleInfos: result.data.knowledgeBaseGroupRoleInfos || {}
        };
        localStorage.setItem('userInfo', JSON.stringify(userData));
        
        // 更新mockData中的currentUser
        const { currentUser } = await import('../data/mockData');
        currentUser.nickname = userData.nickname || '用户';
        currentUser.username = userData.username || 'current_user';
        currentUser.roleId = userData.roleId;
        currentUser.roleName = userData.roleName;
        
        // 触发消息通知获取
        const { eventBus } = await import('../router');
        eventBus.emit('fetch-notifications');
        
        // 跳转到chat页面，但不创建新会话
        router.push({ name: 'chat' });
      } else {
        ToastService.error(result.msg || t('login.failed'));
      }
    } catch (error) {
      console.error(t('login.error'), error);
      ToastService.error(t('login.requestFailed'));
    }
  };
</script>

<template>
  <div class="login-container ai-theme">
    <div class="login-box">
      <h1>{{ t('login.title') }}</h1>
      <form @submit.prevent="handleLogin">
        <div class="input-group">
          <label for="username">{{ t('login.username') }}</label>
          <input 
            id="username" 
            type="text" 
            v-model="username" 
            :placeholder="t('login.usernamePlaceholder')"
            class="ai-input"
          />
        </div>
        <div class="input-group">
          <label for="password">{{ t('login.password') }}</label>
          <input 
            id="password" 
            type="password" 
            v-model="password" 
            :placeholder="t('login.passwordPlaceholder')"
            class="ai-input"
          />
        </div>
        <button type="submit" class="ai-button">{{ t('login.submit') }}</button>
      </form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: url('/images/ai-agent-bg.jpg') center/cover no-repeat;
  position: relative;
}

.language-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 8px 12px;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.login-box {
  background: rgba(255, 255, 255, 0.85);
  padding: 2.5rem;
  border-radius: 15px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
  width: 380px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: #2c3e50;
  font-size: 2rem;
  font-weight: 600;
}

.input-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
  font-weight: 500;
}

.ai-input {
  width: 100%;
  padding: 1rem;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.9);
}

.ai-input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

.ai-button {
  width: 100%;
  padding: 1rem;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 1rem;
}

.ai-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
</style>